/****************************************************
          File Name:46-1-msgrcv.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Thu 11 Sep 2014 04:17:49 PM CST
*****************************************************/

#include"msg.h"
#include<string.h>

int main(int argc,char *argv[])
{
    if(strcmp(argv[1],"--help")==0)
    {
        printf("%s msgid -t mtype (-f [n|e|p])\n",argv[0]);
        exit(1);
    }

    struct msgbuf msgp;
    int flag=0,status;
    int msgid,opt;
    long msgtyp;

    msgid=atoi(argv[1]);
    while((opt=getopt(argc,argv,"f:t:"))!=-1)
    {
        switch(opt)
        {
            case 'f':
                if(optarg[0]=='n')
                    flag|=IPC_NOWAIT;
                if(optarg[0]=='p')
#ifdef MSG_EXCEPT
                    flag|=MSG_EXCEPT;
#endif
                if(optarg[0]=='e')
                    flag|=MSG_NOERROR;
                break;
            case 't':
                if(argv[optind]!=NULL)
                    msgtyp=atol(argv[optind]);
                else
                    msgtyp=0;
                break;
        }
    }

    status=msgrcv(msgid,&msgp,DATA_SIZE,msgtyp,flag);
    if(status==-1)
        err("msgrcv");

    printf("%s\n",msgp.mtext);
    exit(0);
}
